/**
 *  *2010-7-11 下午08:08:54  add 
 */
package com.base.myproject.client.HR.gcode;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseStoreEvent;
import com.base.myproject.client.busi.BaseStoreListener;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.business.BaseRatifyDialogX;
import com.base.myproject.client.busi.business.BusinessRatify;
import com.base.myproject.client.busi.business.RatifyInfo;
import com.base.myproject.client.busi.print.PrintDialogX;
import com.base.myproject.client.busi.print.Printer;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncGetModelDatas;
import com.base.myproject.client.tools.CommandSyncMakeCode;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.dialog.SelectItemDialog;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;

/**
 * 物品领用，有审批
 * 
 * @author Administrator 2010-7-11 javazgw@gmail.com
 */
public class GetGoods extends BaseJDBCPanel implements BusinessRatify ,Printer{
	TextField<String> codename_t = new TextField<String>();
	
	Button getgoods = new Button("选择物品");
	public GetGoods() {
		init();

	}

	public void init() {
		 busi ="7001";
		 flowname = "simple1";
		initWidgetx();
	
		registerMainStore(store);
		registerStore(store);
		registerStore(gooddetail_store);
	}

	private void initWidgetx() {
		VerticalPanel v = new VerticalPanel();
//		v.add(createGrid1());
		v.add(createForm());
		v.add(createGrid());
		this.add(v);
	}

	public void complete() {
		super.complete(); 
		print.addListener(Events.Select, getListener());
		ttiratify.setText("提交确认");
	
		getToolbarll().add(print);
		getToolbarll().add(ttiratify);
		getToolbarll().remove(fresh);
		//ttiratify.addListener(Events.Select, getListener());
	}

	private void setdefault() {
		store.addDefault("busicode", busi);
		store.addDefault("bcode", Env.getEnvbcode());
		//gooddetail_store.addDefault("busicode", "7001");
	}

	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("busicode");
		type.getField("busicode").setType(String.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("busistatus");
		type.getField("busistatus").setType(String.class);
		type.addField("predate");
		type.getField("predate").setType(Date.class);
		type.addField("vprepare");
		type.getField("vprepare").setType(String.class);
		type.addField("modifydate");
		type.getField("modifydate").setType(Date.class);
		type.addField("codename");
		type.getField("codename").setType(String.class);
		type.addField("mark");
		type.getField("mark").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_goods_get");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_goods_get ");
		// info.setParent(mainstore);// 关联主表
		// info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		// info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		store = new BaseStore<BusiObject>(type, info, false);
		store.addBaseStoreListener(BaseStoreEvent.EventType.ROW_ADDED,
				getBasestoreListener());
		
		
		
		setdefault();
		store.addX();
		
		return store;
	}
	



	BaseFormPanel form = null;

	BaseFormPanel createForm() {
		BaseFormPanel form = new BaseFormPanel(getStore());
		TableLayout tl = new TableLayout(4);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);

//		form.add(new Label("icode:"), td);
//		NumberField C_num1 = new NumberField();
//		C_num1.setPropertyEditorType(Long.class);
//		C_num1.setName("icode");
//		form.add(C_num1, td);
//		form.add(new Label("busicode:"), td);
//		TextField<String> C_num2 = new TextField<String>();
//		C_num2.setName("busicode");
//		form.add(C_num2, td);
		form.add(new Label("人员:"), td);
		BaseComboBoxForm<BaseModelData> C_num3 = new BaseComboBoxForm<BaseModelData>("bcode","bname","bcode"," where bcode is not null",true);
		
//		C2.setRenderer(bsb2);
		C_num3.setName("bcode");
		form.add(C_num3, td);
		form.add(new Label("状态:"), td);
		TextField<String> C_num4 = new TextField<String>();
		C_num4.setName("busistatus");
		C_num4.setEnabled(false);
		form.add(C_num4, td);
		form.add(new Label("制单日期:"), td);
		DateField C_data5 = new DateField();
		C_data5.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		C_data5.setName("predate");
		form.add(C_data5, td);
//		form.add(new Label("vprepare:"), td);
//		TextField<String> C_num6 = new TextField<String>();
//		C_num6.setName("vprepare");
//		form.add(C_num6, td);
		form.add(new Label("最后修改日期:"), td);
		DateField C_data7 = new DateField();
		C_data7.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		C_data7.setName("modifydate");
		form.add(C_data7, td);
		form.add(new Label("单据编码:"), td);

		codename_t.setName("codename");
		form.add(codename_t, td);
		form.add(new Label("备注:"), td);
		TextField<String> C_num9 = new TextField<String>();
		C_num9.setName("mark");
		form.add(C_num9, td);
		
		
		form.add(getgoods, td);
		getgoods.addListener(Events.Select, getListener());
		form.inited(140);
		return form;
	};

	BaseStore<BusiObject> gooddetail_store = null;

	BaseStore<BusiObject> get_detail_store() {
		if (gooddetail_store == null) {
			create_detail_stroe();
		}
		return gooddetail_store;
	}

	BaseStore<BusiObject> create_detail_stroe() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("goodscode");
		type.getField("goodscode").setType(String.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		type.addField("status");
		type.getField("status").setType(String.class);
		type.addField("qty");
		type.getField("qty").setType(Integer.class);
		type.addField("qtyunit");
		type.getField("qtyunit").setType(String.class);
		type.addField("dc");
		type.getField("dc").setType(Integer.class);
		type.addField("lostamount");
		type.getField("lostamount").setType(Double.class);
		type.addField("damageamount");
		type.getField("damageamount").setType(Double.class);
		type.addField("mdc");
		type.getField("mdc").setType(Integer.class);
		type.addField("upcode");
		type.getField("upcode").setType(String.class);
		type.addField("busicode");
		type.getField("busicode").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_goodsdetail");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_goodsdetail where upcode='{codename}'");
		info.setParent(store);// 关联主表
		info.setLinkparentcolumns(new String[] { "codename" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "upcode" });// 关联主表字段
		gooddetail_store = new BaseStore<BusiObject>(type, info);
		gooddetail_store.addDefault("busicode", busi);
		gooddetail_store.addDefault("bcode", Env.getEnvbcode());
		return gooddetail_store;
	}

	BaseGridPanel gooddetail_grid = null;

	BaseGridPanel createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

//		ColumnConfig C1 = new ColumnConfig("icode", "icode", 80);
//		columns.add(C1);
		ColumnConfig C2 = new ColumnConfig("goodscode", "物品", 150);
		columns.add(C2);
//		ColumnConfig C3 = new ColumnConfig("bcode", "bcode", 80);
//		columns.add(C3);
//		ColumnConfig C4 = new ColumnConfig("createdate", "createdate", 80);
//		columns.add(C4);
//		ColumnConfig C5 = new ColumnConfig("status", "status", 80);
//		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("qty", "数量", 100);
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("qtyunit", "数量单位", 80);
		columns.add(C7);
		/*ColumnConfig C8 = new ColumnConfig("dc", "dc", 80);
		columns.add(C8);
		ColumnConfig C9 = new ColumnConfig("lostamount", "lostamount", 80);
		columns.add(C9);
		ColumnConfig C10 = new ColumnConfig("damageamount", "damageamount", 80);
		columns.add(C10);
		ColumnConfig C11 = new ColumnConfig("mdc", "mdc", 80);
		columns.add(C11);
		ColumnConfig C12 = new ColumnConfig("upcode", "upcode", 80);
		columns.add(C12);
		ColumnConfig C13 = new ColumnConfig("busicode", "busicode", 80);
		columns.add(C13);*/

		ColumnModel cm = new ColumnModel(columns);
		gooddetail_grid = new BaseGridPanel(get_detail_store(), cm,true,true)
		{
			protected void addnewrecord() {
				addrecord();
				
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		gooddetail_grid.getBg().setSelectionModel(cbs);
		gooddetail_grid.getBg().setHeight(300);
		return gooddetail_grid;
	}

	void addrecord()
	{
		 SelectItemDialog s= new SelectItemDialog()
		 
		 {
				@SuppressWarnings("unchecked")
				protected void onOK()
				{
					 super.onOK();
					 //注意grid是SelectItemDialog里的grid
					for(BusiObject bo: grid.getSelectionModel().getSelectedItems())
					{
						HashMap hm = new HashMap();
						hm.put("goodscode", bo.get("code"));
						hm.put("qtyunit", bo.get("qtyunit"));
						hm.put("qty", 1);
						hm.put("status", 40);
						get_detail_store().add(hm);
						
					}
				}
		 };
		 s.setSelectmode(2);
		 s.setColumndisplayname(new String[]{"编码","名称","单位"});
		 s.setColumnname(new String[]{"code","name","qtyunit",});
		 CommandSyncGetModelDatas csgmd2 = new CommandSyncGetModelDatas();
		 csgmd2.setSqlname("hr_goods_goods");
		 s.setCsgmd2(csgmd2);
		 s.show();
	}
	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							if (be.getSource().equals(ttiratify)) {

								if(store.getValue("icode")==null)
								{
									MessageBox.alert("错误", "不能进行提交。icode数据为空。", null);
									return;
								}
								RatifyInfo ratifyinfo = new RatifyInfo();
								ratifyinfo.setBusi(busi);
								ratifyinfo.setIcode(store.getValue("icode")+"");
								ratifyinfo.setFlowname("simple1");
								BaseRatifyDialogX bdx = new BaseRatifyDialogX(ratifyinfo);
								bdx.show();
							}
							else if(be.getSource().equals(getgoods))
							{
								addrecord();
							}
							else if (be.getSource() == print) {
								

								Print() ;
							
							
							}
						} else if (be.getType() == Events.Change) {
							if (be.getSource().equals("")) {

							}
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}

	private BaseStoreListener getBasestoreListener() {
		BaseStoreListener listener = new BaseStoreListener() {

			@Override
			public void BaseStoreEventHandle(final BaseStoreEvent evt) {

				if (evt.getEventType().equals(
						BaseStoreEvent.EventType.ROW_ADDED)) {

					final int rowindex = evt.getBasestore().getCurcowindex();

					CommandSyncContainer list = new CommandSyncContainer();
					CommandSyncMakeCode csmc = new CommandSyncMakeCode();

					csmc.setBeginstr("c");
					csmc.setColumnname("codename");
					csmc.setTablename("hr_goods_get");
					list.add(csmc);

					final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
							.create(com.base.myproject.client.tools.GreetingService.class);
					greetingService.SendCommandSync(list,
							new AsyncCallback<CommandSyncReturnObject>() {
								public void onFailure(Throwable caught) {
									Window.alert("网络连接不稳定，请稍后重试！");
								}

								public void onSuccess(
										CommandSyncReturnObject cyro) {

									if (cyro.isB()) {
										// GWT.log("codename="+cyro.getRetrunstr()+" rowindex="+rowindex+""+evt.getBasestore().getValue("icode"));
										 evt.getBasestore().setValue(rowindex,
										 "codename", cyro.getRetrunstr());

										store.trySave();
										store.gotorow(0);
//								
									} else {
										Window.alert("分配内码时出错。");
									}
								}
							});
				}
			}

			@Override
			public void onBrowserEvent(Event event) {

			}

		};

		return listener;
	}
	protected void ratify()
	{
		super.ratify();
	}
	
	@Override
	public boolean AfterRatify() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean BeforeRatify() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean OnRatify() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void Print() { 
		printer();
	}
	
	
	private void printer()
	{
		
		
		if(store.getValue("icode")==null)
		{
			MessageBox.alert("错误", "未选择打印单。", null);
			return;
		}
		String icode =store.getValue("icode").toString();
		PrintDialogX printdialog = new PrintDialogX(busi,"&innercode="+icode);
		printdialog.show();

	}

}
